package com.qixiucoding.config;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.json.JsonParser;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;

import java.io.*;

/**
 * @Description 获取json配置工具类
 * @Author longhj
 * @Date 2021/11/20 星期六 22:53
 */

@Slf4j
public class JSONHelper {
    /**
     * 将文件流转为json对象，文件存放路径与配置文件路径规范一致
     *
     * @param
     * @return
     * @throws
     */
    public static Object resolveJsonFileToObject(String filename) {
        String str = ResolveJsonFileToString(filename);
        JSONObject jo = JSONObject.parseObject(str);
        return jo;
    }
    /**
     * 将文件流转为json对象，文件存放路径与配置文件路径规范一致
     *
     * @param
     * @return
     * @throws
     */
    public static <T> T resolveJsonFileToJsonObject(String filename,Class<T> clazz) {
        String str = ResolveJsonFileToString(filename);

        return JSONObject.parseObject(str,clazz, Feature.AllowComment);
    }
    /**
     * 通过字节数组将文件流转为json对象，文件存放路径与配置文件路径规范一致
     *
     * @param
     * @return
     * @throws
     */
    public static <T> T resolveJsonFileByByteToJsonObject(String filename,Class<T> clazz) {
        byte[] bArray = file2byte(filename);

        return JSONObject.parseObject(bArray,clazz, Feature.AllowComment,Feature. AllowUnQuotedFieldNames, Feature.AllowSingleQuotes,Feature.OrderedField,Feature.UseBigDecimal);
    }
    /**
     * 将文件转换成byte数组
     * @param filename
     * @return
     */
    public static byte[] file2byte(String filename){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = getResFileStream(filename);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 通过文件名获取获取json格式字符串，
     *
     * @param filename 文件存放路径与配置文件路径规范一致
     * @return ResolveJsonFileToString
     * @throws
     */
    public static String ResolveJsonFileToString(String filename) {

        BufferedReader br = null;
        String result = null;
        try {

//            br = new BufferedReader(new InputStreamReader(getInputStream(path)));
            br = new BufferedReader(new InputStreamReader(getResFileStream(filename), "UTF-8"));
            StringBuffer message = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                message.append(line);
            }
            if (br != null) {
                br.close();
            }
            String defaultString = message.toString();
            result = defaultString.replace("\r\n", "").replaceAll(" +", "");
            log.info("result={}", result);

        } catch (IOException e) {
            try {
                ClassLoader classloader = Thread.currentThread().getContextClassLoader();
                InputStream in = classloader.getResourceAsStream(filename);
                br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuffer message = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    message.append(line);
                }
                if (br != null) {
                    br.close();
                }
                if (in != null) {
                    in.close();
                }
                String defaultString = message.toString();
                result = defaultString.replace("\r\n", "").replaceAll(" +", "");
                log.debug("for jar result={}", result);
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }

        return result;
    }


    private static File getResFile(String filename) throws FileNotFoundException {
        File file = new File(filename);

        Resource resource = new FileSystemResource(file);
        //config目录下还是找不到，那就直接用classpath下的
        if (!resource.exists()) {
            log.debug("不在config目录，进入classpath目录查找");
            file = ResourceUtils.getFile("classpath:" + filename);
        }
        // 如果同级目录没有，则去config下面找
        if (!file.exists()) {
            log.debug("不在同级目录，进入config目录查找");
            file = new File("config/" + filename);
        }
        return file;
    }

    /**
     * 通过文件名获取classpath路径下的文件流
     *
     * @param
     * @return
     * @throws
     */
    private static FileInputStream getResFileStream(String filename) throws FileNotFoundException {
        FileInputStream fin = null;
        File file = getResFile(filename);
        log.info("getResFile path={}", file);
        fin = new FileInputStream(file);
        return fin;
    }

}

